package com.ufo.store.management.ui.activity;

import android.animation.ObjectAnimator;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ufo.store.management.R;
import com.ufo.store.management.adapter.MemberViewPagerAdapter;
import com.ufo.store.management.ui.fragment.MemberListFragment;
import com.ufo.store.management.common.Config;
import com.ufo.store.management.utils.StatusBarUtil;
import com.ufo.store.management.utils.Utils;
import com.ufo.store.management.BarApplication;

import java.util.ArrayList;
import java.util.List;

import com.ufo.store.management.widget.MagicIndicator.titles.ColorFlipPagerTitleView;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

/**
 * Created by Administrator on 2015/9/25 0025.
 */
public class MemberActivity extends BaseActivity  {
    public static final String TAG = MemberActivity.class.getSimpleName();
    // View name of the header image. Used for activity scene transitions
    public static final String VIEW_NAME_HEADER_IMAGE = "detail:header:image";

    public PopupWindow mModeSelectPopWindow = null;

    private ImageView mReturnIv = null;
    private RelativeLayout search_rl = null;
    private TextView mSearchTv = null;

    private LinearLayout mTitleLl;
    private MagicIndicator mMagicIndicator;
    private RelativeLayout condition_rl;
    private ImageView styleIv;
    private RelativeLayout mContentRl;

    private TextView name_tv;
    private TextView accumulate_points_tv;
    private TextView consumption_tv;

    private ImageView name_iv;
    private ImageView accumulate_points_iv;
    private ImageView consumption_iv;

    private ViewPager mViewPager;
    private MemberViewPagerAdapter mMemberViewPagerAdapter;

    private List<String> mMemberPointValueList = new ArrayList<String>();
    private List<String> mMemberPointNameList = new ArrayList<String>();

    private int mMaxMemberCount = -1;

    private boolean mIsTitleLlHided = false;

    private int mMoveStartY = 0;
    private int mMoveDurY = 0;

    private FloatingActionButton mFloatingActionButton;

    private int ListStyle = 1;

    private int SortMode = -1;     // 0:姓名升序   1：姓名降序    2：积分升序  3：积分降序    4：消费升序     5：消费降序

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
        StatusBarUtil.StatusBarLightMode(this,R.color.app_bar_color,true);
    }

    private void initData() {
        mMemberPointNameList.clear();
        mMemberPointNameList.add("全部");
        mMemberPointNameList.add("见习会员");
        mMemberPointNameList.add("新晋会员");
        mMemberPointNameList.add("卓越会员");
        mMemberPointNameList.add("资深会员");
        mMemberPointNameList.add("殿堂会员");
        mMemberPointValueList.clear();
        mMemberPointValueList.add("0");
        mMemberPointValueList.add("50");
        mMemberPointValueList.add("100");
        mMemberPointValueList.add("250");
        mMemberPointValueList.add("500");
        mMemberPointValueList.add("700");

        ListStyle = Config.getFastfoodMemberListStyle();
    }

    private void initView() {
        setContentView(R.layout.activity_member);
        mReturnIv = (ImageView) findViewById(R.id.iv_back);
        mReturnIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishAfterTransition();
            }
        });
        search_rl = (RelativeLayout)findViewById(R.id.search_rl);
        mTitleLl = (LinearLayout) findViewById(R.id.title_bar);
        condition_rl = (RelativeLayout) findViewById(R.id.condition_rl);
        styleIv = (ImageView)findViewById(R.id.style_iv);
        mContentRl = (RelativeLayout)findViewById(R.id.content_rl);

        name_tv = (TextView) findViewById(R.id.name_tv);
        accumulate_points_tv = (TextView) findViewById(R.id.accumulate_points_tv);
        consumption_tv = (TextView) findViewById(R.id.consumption_tv);

        name_iv = (ImageView) findViewById(R.id.name_iv);
        accumulate_points_iv = (ImageView) findViewById(R.id.accumulate_points_iv);
        consumption_iv = (ImageView) findViewById(R.id.consumption_iv);

        styleIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if( ListStyle == 1 ){
                    ListStyle = 2;
                    styleIv.setImageResource(R.drawable.ic_grid_style_selector);
                }else if( ListStyle == 2 ){
                    ListStyle = 1;
                    styleIv.setImageResource(R.drawable.ic_list_style_selector);
                }

                Config.setFastfoodMemberListStyle(ListStyle);
                mMemberViewPagerAdapter.setStyle(ListStyle);
            }
        });

        name_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                name_tv.setTextColor(getResources().getColor(R.color.app_key_color));
//                accumulate_points_tv.setTextColor(Color.parseColor("#5c5c5c"));
//                consumption_tv.setTextColor(Color.parseColor("#5c5c5c"));
                name_iv.setImageResource(R.drawable.ic_triangle_press);
                accumulate_points_iv.setImageResource(R.drawable.ic_triangle_dark);
                consumption_iv.setImageResource(R.drawable.ic_triangle_dark);
                if( SortMode != 0 ) {
                    SortMode = 0;
                    name_iv.animate().rotation(180);
                }else{
                    SortMode = 1;
                    name_iv.animate().rotation(0);
                }
                accumulate_points_iv.animate().rotation(0);
                consumption_iv.animate().rotation(0);
                mMemberViewPagerAdapter.setSearchSortMode(SortMode);
            }
        });
        accumulate_points_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                name_tv.setTextColor(Color.parseColor("#5c5c5c"));
//                accumulate_points_tv.setTextColor(getResources().getColor(R.color.app_key_color));
//                consumption_tv.setTextColor(Color.parseColor("#5c5c5c"));
                name_iv.setImageResource(R.drawable.ic_triangle_dark);
                accumulate_points_iv.setImageResource(R.drawable.ic_triangle_press);
                consumption_iv.setImageResource(R.drawable.ic_triangle_dark);
                name_iv.animate().rotation(0);
                if( SortMode != 2 ) {
                    SortMode = 2;
                    accumulate_points_iv.animate().rotation(180);
                }else {
                    SortMode = 3;
                    accumulate_points_iv.animate().rotation(0);
                }
                consumption_iv.animate().rotation(0);
                mMemberViewPagerAdapter.setSearchSortMode(SortMode);
            }
        });
        consumption_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                name_tv.setTextColor(Color.parseColor("#5c5c5c"));
//                accumulate_points_tv.setTextColor(Color.parseColor("#5c5c5c"));
//                consumption_tv.setTextColor(getResources().getColor(R.color.app_key_color));
                name_iv.setImageResource(R.drawable.ic_triangle_dark);
                accumulate_points_iv.setImageResource(R.drawable.ic_triangle_dark);
                consumption_iv.setImageResource(R.drawable.ic_triangle_press);
                name_iv.animate().rotation(0);
                accumulate_points_iv.animate().rotation(0);
                if( SortMode != 4 ) {
                    SortMode = 4;
                    consumption_iv.animate().rotation(180);
                }else {
                    SortMode = 5;
                    consumption_iv.animate().rotation(0);
                }
                mMemberViewPagerAdapter.setSearchSortMode(SortMode);
            }
        });

        if( ListStyle == 2 ){
            styleIv.setImageResource(R.drawable.ic_grid_style_selector);
        }else if( ListStyle == 1 ){
            styleIv.setImageResource(R.drawable.ic_list_style_selector);
        }

        mFloatingActionButton = (FloatingActionButton) findViewById(R.id.floating_action_bt);
        mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startInsertMemberActivity();
            }
        });

        mSearchTv = (TextView) findViewById(R.id.search_tv);
        mReturnIv = (ImageView) findViewById(R.id.iv_back);
        mReturnIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        search_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //展开选项菜单
//                if (!mModeSelectPopWindow.isShowing()) {
//                    mModeSelectPopWindow.showAsDropDown(v, -1 * (int) getResources().getDimension(R.dimen.setting_popup_xoff), 0);
//                } else {
//                    mModeSelectPopWindow.dismiss();
//                }
                startSearchMemberActivity();
            }
        });

        mViewPager = (ViewPager)findViewById(R.id.viewpager);
        mMemberViewPagerAdapter = new MemberViewPagerAdapter(getSupportFragmentManager());
        mMemberViewPagerAdapter.setMemberPointList(mMemberPointValueList);
        mMemberViewPagerAdapter.setMemberListStyle(ListStyle);
        mMemberViewPagerAdapter.setMemberListGetProcessListener(new MemberListFragment.MemberListGetProcessListener() {
            @Override
            public void onMemberMaxIndexProcessFinish(int maxMemberIndex) {
                mSearchTv.setText("搜索" + String.valueOf(maxMemberIndex) + "名会员");
            }

            @Override
            public void onMemberIndexProcessFinish(int maxMemberCountByPoint, int position) {
                if( mMemberViewPagerAdapter.isFragmentVisible( position ) ){
                    mMaxMemberCount = maxMemberCountByPoint;
                }
            }

            @Override
            public void onMemberListViewTouchEvent(MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        mMoveDurY = 0;
                        mMoveStartY = 0;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (mMoveStartY == 0) {
                            mMoveStartY = (int) event.getY();
                        }
                        int _TempY = (int) event.getY();
                        mMoveDurY = _TempY - mMoveStartY;   //负数向上移动，正数向下移动
                        if (mMoveDurY < -Utils.dp2px(getResources(), 80) && mIsTitleLlHided == false) {
                            mMoveDurY = 0;
                            mMoveStartY = 0;
                            mIsTitleLlHided = true;
                            mMemberViewPagerAdapter.setTitleIsHided(true);
                            menuCollapse();
                        } else if (mMoveDurY > Utils.dp2px(getResources(), 80) && mIsTitleLlHided == true) {
                            mMoveDurY = 0;
                            mMoveStartY = 0;
                            mIsTitleLlHided = false;
                            mMemberViewPagerAdapter.setTitleIsHided(false);
                            menuExpand();
                        }
                        break;
                }
            }
        });
        mViewPager.setAdapter(mMemberViewPagerAdapter);
        mViewPager.setCurrentItem(0);
        mViewPager.setOffscreenPageLimit(10);

        mMagicIndicator = (MagicIndicator)findViewById(R.id.id_indicator);
        initMagicIndicator(mMemberPointNameList);

        //setPopWindow();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
//            if (mModeSelectPopWindow != null && mModeSelectPopWindow.isShowing()) {
//                mModeSelectPopWindow.dismiss();
//                return true;
//            }
//            return super.onKeyDown(keyCode, event);
            finishAfterTransition();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initMagicIndicator(final List<String> dataList) {
        CommonNavigator commonNavigator7 = new CommonNavigator(this);
        commonNavigator7.setScrollPivotX(0.65f);
        commonNavigator7.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return dataList == null ? 0 : dataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ColorFlipPagerTitleView(context);
                simplePagerTitleView.setText(dataList.get(index));
                simplePagerTitleView.setNormalColor(Color.parseColor("#5c5c5c"));
                simplePagerTitleView.setSelectedColor(Color.parseColor("#2c2c2c"));
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mViewPager.setCurrentItem(index);
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setLineHeight(UIUtil.dip2px(context, 6));
                indicator.setLineWidth(UIUtil.dip2px(context, 10));
                indicator.setRoundRadius(UIUtil.dip2px(context, 3));
                indicator.setStartInterpolator(new AccelerateInterpolator());
                indicator.setEndInterpolator(new DecelerateInterpolator(2.0f));
                indicator.setColors(getResources().getColor(R.color.app_key_color));
                return indicator;
            }
        });
        mMagicIndicator.setNavigator(commonNavigator7);
        ViewPagerHelper.bind(mMagicIndicator, mViewPager);
    }

    private void startInsertMemberActivity() {
        if (BarApplication.getInstance().mDatabaseIsSqlServer) {
            Intent toIntent = new Intent(MemberActivity.this, MemberEditActivity.class);
            Bundle bundle = new Bundle();
            toIntent.putExtras(bundle);
            startActivity(toIntent);
        }
    }

    private void startSearchMemberActivity() {
        Intent toIntent = new Intent(MemberActivity.this, SearchMemberActivity.class);
        Bundle bundle = new Bundle();
        toIntent.putExtras(bundle);
        //startActivity(toIntent);
        @SuppressWarnings("unchecked")
        ActivityOptions activityOptions = ActivityOptions.makeSceneTransitionAnimation(
                MemberActivity.this,
                // Now we provide a list of Pair items which contain the view we can transitioning
                // from, and the name of the view it is transitioning to, in the launched activity
                findViewById(R.id.search_rl), "searchbar");
        startActivity(toIntent, activityOptions.toBundle());
    }

    private android.animation.Animator mAnimatorTitle;
    private android.animation.Animator mAnimatorSv;
    private android.animation.Animator mAnimatorCondition;
    private android.animation.Animator mAnimatorContent;
    private android.animation.Animator mAnimatorAction;

    /**
     * @desc  动画隐藏标题栏，true 显示， false 隐藏
     * @author taoli
     * @time 2017/2/15 0015
     */
    private void showHideTitleBar(boolean tag) {
        if (mAnimatorTitle != null && mAnimatorTitle.isRunning()) {
            mAnimatorTitle.cancel();
        }
        if (mAnimatorSv != null && mAnimatorSv.isRunning()) {
            mAnimatorSv.cancel();
        }
        if (mAnimatorCondition != null && mAnimatorCondition.isRunning()) {
            mAnimatorCondition.cancel();
        }
        if (mAnimatorContent != null && mAnimatorContent.isRunning()) {
            mAnimatorContent.cancel();
        }
        if (mAnimatorAction != null && mAnimatorAction.isRunning()) {
            mAnimatorAction.cancel();
        }
        if (tag) {
            mAnimatorTitle = ObjectAnimator.ofFloat(mTitleLl, "translationY", mTitleLl.getTranslationY(), 0);
            mAnimatorTitle.setStartDelay(120);
            mAnimatorSv = ObjectAnimator.ofFloat(mMagicIndicator, "translationY", mMagicIndicator.getTranslationY(), getResources().getDimension(R.dimen.member_title_height));
            mAnimatorSv.setStartDelay(80);
            mAnimatorCondition = ObjectAnimator.ofFloat(condition_rl, "translationY", condition_rl.getTranslationY(), getResources().getDimension(R.dimen.member_title_point_height));
            mAnimatorCondition.setStartDelay(40);
            mAnimatorContent = ObjectAnimator.ofFloat(mContentRl, "translationY", mContentRl.getTranslationY(), getResources().getDimension(R.dimen.member_title_point_height));
            mAnimatorAction = ObjectAnimator.ofFloat(mFloatingActionButton, "translationY", mFloatingActionButton.getTranslationY(),0);
        } else {
            mAnimatorTitle = ObjectAnimator.ofFloat(mTitleLl, "translationY", mTitleLl.getTranslationY(), -getResources().getDimension(R.dimen.member_title_height));
            mAnimatorSv = ObjectAnimator.ofFloat(mMagicIndicator, "translationY", mMagicIndicator.getTranslationY(), -getResources().getDimension(R.dimen.member_point_height));
            mAnimatorSv.setStartDelay(40);
            mAnimatorCondition = ObjectAnimator.ofFloat(condition_rl, "translationY", condition_rl.getTranslationY(), 0);
            mAnimatorCondition.setStartDelay(80);
            mAnimatorContent = ObjectAnimator.ofFloat(mContentRl, "translationY", mContentRl.getTranslationY(), 0);
            mAnimatorContent.setStartDelay(120);
            mAnimatorAction = ObjectAnimator.ofFloat(mFloatingActionButton, "translationY", mFloatingActionButton.getTranslationY(), getResources().getDimension(R.dimen.action_dis) + mFloatingActionButton.getHeight());
        }
        mAnimatorTitle.start();
        mAnimatorSv.start();
        mAnimatorCondition.start();
        mAnimatorContent.start();
        mAnimatorAction.start();
    }

    /**
     * @desc  隐藏
     * @author taoli
     * @time 2017/2/15 0015
     */
    private void menuCollapse() {
        showHideTitleBar(false);
    }

    /**
     * @desc  显示
     * @author taoli
     * @time 2017/2/15 0015
     */
    private void menuExpand() {
        showHideTitleBar(true);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mModeSelectPopWindow != null && mModeSelectPopWindow.isShowing()) {
            mModeSelectPopWindow.dismiss();
            return true;
        }
        return super.dispatchTouchEvent(ev);
    }

    private void setPopWindow() {
        View main_popup_window = LayoutInflater.from(this.getApplicationContext()).inflate(R.layout.pop_member_operate_select, null);
        mModeSelectPopWindow = new PopupWindow(main_popup_window, (int) getResources().getDimension(R.dimen.setting_popup_width), ViewGroup.LayoutParams.WRAP_CONTENT);
        mModeSelectPopWindow.setAnimationStyle(R.style.pop_window_anim_right_style);
        main_popup_window.findViewById(R.id.operate_insert_btn).setOnClickListener(new View.OnClickListener() {
            public final void onClick(View v) {
                startInsertMemberActivity();
                mModeSelectPopWindow.dismiss();
            }
        });
        main_popup_window.findViewById(R.id.operate_search_btn).setOnClickListener(new View.OnClickListener() {
            public final void onClick(View v) {
                startSearchMemberActivity();
                mModeSelectPopWindow.dismiss();
            }
        });

        mModeSelectPopWindow.setBackgroundDrawable(new BitmapDrawable());
        mModeSelectPopWindow.setFocusable(false);
        if (main_popup_window != null) {
            main_popup_window.startAnimation(AnimationUtils.loadAnimation(MemberActivity.this.getApplicationContext(), android.R.anim.fade_in));
        }
    }
}
